//
//  NewInviteViewController.swift
//  xiaoqiao
//
//  Created by 冷子豪 on 2017/8/9.
//  Copyright © 2017年 冷子豪. All rights reserved.
//

import UIKit

//当前二维码
var theQRImage:UIImage = #imageLiteral(resourceName: "QR")

class NewInviteViewController: UIViewController {

    
    @IBOutlet weak var QRImageView: UIImageView!
    override func viewDidLoad() {
        super.viewDidLoad()
        
        //异步加载图片
        let phoneNum:Int? = Int(user.phone!)
        if let url = URL(string: user.inviteLink!) {
            QRImageView.downloadedFrom(url: url)
        }

    }

    
    @IBAction func shareButtonClick(_ sender: UIBarButtonItem) {
        let alertController = MyAlertController(title: "", message: "分享至：", preferredStyle: .actionSheet)
        
        let weixinAction = UIAlertAction(title: "微信好友", style: .default, handler: {
            action in
            //分享至微信好友
            print("微信")
        })
        
        let pengyouquanAction = UIAlertAction(title: "朋友圈", style: .default, handler: {
            action in
            //分享至朋友圈
            print("朋友圈")
        })
        
        let messageAction = UIAlertAction(title: "短信", style: .default, handler: {
            action in
            //分享至短信
            print("短信")
        })
        
        let saveAction = UIAlertAction(title: "保存二维码", style: .destructive, handler: {
            action in
            //保存图片
            print("保存")
            UIImageWriteToSavedPhotosAlbum(theQRImage, self, #selector(self.image(image:didFinishSavingWithError:contextInfo:)), nil)

        })
        
        let cancelAction = UIAlertAction(title: "取消", style: .cancel, handler: {
            action in
            //取消
            print("取消")
        })
        
        
        alertController.addAction(weixinAction)
        alertController.addAction(pengyouquanAction)
        alertController.addAction(messageAction)
        alertController.addAction(saveAction)
        alertController.addAction(cancelAction)
        
        self.present(alertController, animated: true, completion: nil)
    }
    
    /// 保存图片
    ///
    /// - Parameters:
    ///   - image: <#image description#>
    ///   - error: <#error description#>
    ///   - contextInfo: <#contextInfo description#>
    func image(image:UIImage,didFinishSavingWithError error:NSError?,contextInfo:AnyObject) {
        
        if error != nil {
            print("保存失败")
        } else {
            print("保存成功")
        }
    }
}

extension UIImageView {
    func downloadedFrom(url: URL, contentMode mode: UIViewContentMode = .scaleToFill){
        contentMode = mode
        URLSession.shared.dataTask(with: url) { (data, response, error) in
            // The download has finished.
            if let e = error {
                print("Error downloading cat picture: \(e)")
            } else {
                // No errors found.
                // It would be weird if we didn't have a response, so check for that too.
                if let res = response as? HTTPURLResponse {
                    print("Downloaded cat picture with response code \(res.statusCode)")
                    if let imageData = data {
                        // Finally convert that Data into an image and do what you wish with it.
                        let image = UIImage(data: imageData)
                        theQRImage = image!
                        // Do something with your image.
                        DispatchQueue.main.async() { () -> Void in
                            self.image = image
                        }
                        
                    } else {
                        print("Couldn't get image: Image is nil")
                    }
                } else {
                    print("Couldn't get response code for some reason")
                }
            }
            
            }.resume()
        
    }
    func downloadedFrom(link: String, contentMode mode: UIViewContentMode = .scaleAspectFit) {
        guard let url = URL(string: link) else { return }
        downloadedFrom(url: url, contentMode: mode)
    }
}
